<?php

class Mailer
{
	private $sender;
	
	private $mailer;

	private $last;

	/**
	 * @param  array $key
	 * @return Mailer
	 */
	public static function fromConfig($key)
	{
		$config = AgaviConfig::get($key);

		return new Mailer($config['sender'], $config['host'], $config['port'], $config['user'], $config['pass'], empty($config['security']) ? null : $config['security']);
	}

	public function __construct($sender, $host, $port, $user, $pass, $security = null)
	{
		$this->sender = $sender;

		$transport = Swift_SmtpTransport::newInstance($host, $port, $security)
			->setUsername($user)
			->setPassword($pass);
		
		$this->mailer = Swift_Mailer::newInstance($transport);
	}

	/**
	 * @param  string $subject
	 * @return Swift_Message
	 */
	public function createMessage($subject)
	{
		return $this->last = Swift_Message::newInstance($subject)
			->setFrom($this->sender);
	}

	/**
	 * @param  Swift_Message? $message
	 * @return int
	 */
	public function send(Swift_Message $message = null)
	{
		if ($message === null && $this->last === null)
		{
			throw new BadMethodCallException('No e-mail message specified.');
		}

		$result = $this->mailer->send($message ?: $this->last);

		$this->last = null;

		return $result;
	}
}